/**  
 * @Title: DataXComp.java
 * @Description: TODO(描述)
 * @author liuyi
 * @date 2023-04-13 16:21:25 
 */  
package com.fsxgt.datagrid.component.handler.impl;

import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONPath;
import com.fsxgt.datagrid.component.bo.CmpHttpRequestBO;
import com.fsxgt.datagrid.ds.utils.ParamUtil;
import com.fsxgt.datagrid.flow.exception.FlowException;
import com.fsxgt.datagrid.flow.handler.FlowContext;
import com.fsxgt.datagrid.flow.handler.FlowReturn;
import com.fsxgt.datagrid.flow.handler.IComponentHandler;

import lombok.extern.slf4j.Slf4j;

/**  
 * @ClassName: DataxComponent
 * @Description: TODO(描述)
 * @author liuyi
 * @date 2023-04-13 16:21:25 
*/
@Slf4j
@Component
public class CmpHttpRequestHandler extends IComponentHandler{
	
	@Autowired
    private RestTemplate restTemplate;

	public FlowReturn handler(final Object config,FlowContext context) throws Exception{
		
		
		CmpHttpRequestBO bo = (CmpHttpRequestBO)config;
		
		HttpHeaders headers = new HttpHeaders();
		
		if(StringUtils.isNotEmpty(bo.getContentType())) {
			headers.add("Content-Type", bo.getContentType());
		}else {
			headers.add("Content-Type", "application/json;charset=UTF-8");
		}
		
		String body=bo.getHttpBody();
		
		body=ParamUtil.transform(body, (Map) context.get(ParamUtil.PARAM_KEY)).getText();
		
		HttpEntity<String> httpEntity = new HttpEntity(body, headers);
		
		String result=null;
		
		if(bo.getRequestType()!=null&&bo.getRequestType().toUpperCase().equals("GET")) {
			result=restTemplate.getForObject(bo.getHttpUrl(), String.class);
		}else {
			result=restTemplate.postForObject(bo.getHttpUrl(), httpEntity, String.class);
		}

		if(StringUtils.isNotEmpty(bo.getAssertPath())) {
			Object v=JSONPath.eval(JSON.parse(result), bo.getAssertPath());
			
			if(StringUtils.isEmpty(bo.getAssertValue())) {
				if(v==null||v.equals("")) {
					throw new FlowException("http断言失败:返回值为"+v);
				}
			}else {
				if(!v.equals(bo.getAssertValue())) {
					throw new FlowException("http断言失败:返回值为"+v);
				}
			}
		}
		
		return new FlowReturn();
	}

	/**  
	 * @Title: getName
	 * @Description: TODO(描述)
	 * @return 
	 * @see com.fsxgt.datagrid.core.handler.ICommonComponentHandler#getName() 
	 * @author liuyi
	 * @date 2023-04-14 13:49:53 
	 */ 
	@Override
	public String getComponentType() {
		// TODO Auto-generated method stub
		return "Http Request";
	}




	@Override
	public void stopHandler(Object config, FlowContext context) throws Exception {
		// TODO Auto-generated method stub
		
	}
	
}
